const hre = require('hardhat');
const fs = require('fs');
const path = require('path');

async function main() {
  // try to read contract address from front utils file
  const utilsPath = path.join(__dirname, '..', '..', 'front', 'src', 'utils', 'crowdfunding.js');
  let addr = null;
  try {
    const txt = fs.readFileSync(utilsPath, 'utf8');
    const m = txt.match(/export const CONTRACT_ADDRESS = ['"](.*?)['"];?/);
    if (m) addr = m[1];
  } catch (e) {
    // ignore
  }
  if (!addr) {
    console.log('No contract address found in front utils, falling back to artifacts (first Crowdfunding deployment)');
    const artifacts = await hre.artifacts.readArtifact('Crowdfunding');
    // no address fallback
  }

  const [deployer, funder] = await hre.ethers.getSigners();
  console.log('Using deployer', await deployer.getAddress());
  console.log('Using funder', await funder.getAddress());

  if (!addr) throw new Error('Contract address not found. Run `npx hardhat run scripts/deploy.js --network localhost` first');

  const Crowdf = await hre.ethers.getContractAt('Crowdfunding', addr, deployer);

  console.log('Creating project...');
  const tx = await Crowdf.connect(deployer).createProject('Test project', hre.ethers.parseEther('1'), 60*60*24);
  await tx.wait();
  console.log('Project created');

  const count = await Crowdf.projectCount();
  console.log('Project count:', count.toString());

  // ethers v6 returns BigInt for uint256 results
  const projectId = count - 1n;
  console.log('Funding project', projectId.toString());
  const fundTx = await Crowdf.connect(funder).fundProject(projectId, { value: hre.ethers.parseEther('0.5') });
  await fundTx.wait();
  console.log('Funded 0.5 ETH');

  const p = await Crowdf.getProject(projectId);
  console.log('AmountRaised (wei):', p.amountRaised.toString());

  console.log('Attempt withdraw (should fail unless goal reached)');
  try {
    const w = await Crowdf.connect(deployer).withdraw(projectId);
    await w.wait();
    console.log('Withdrawn');
  } catch (e) {
    console.log('Withdraw failed as expected:', e.message);
  }
}

main().catch((e)=>{ console.error(e); process.exit(1); });
